package com.cskaoyan.mall.service;

import com.cskaoyan.mall.dao.GoodsDao;
import com.cskaoyan.mall.dao.GoodsDaoImpl;
import com.cskaoyan.mall.model.Goods;
import com.cskaoyan.mall.model.GoodsParam;
import com.cskaoyan.mall.model.Spec;
import com.cskaoyan.mall.model.Type;

import java.util.List;

/**
 * @PackgeName: com.cskaoyan.mall.service
 * @ClassName: GoodsServiceImpl
 * @Author: admin
 * Date: 2020/5/3 20:57
 * project name: Javaproject1
 * @Version:
 * @Description:
 */
public class GoodsServiceImpl implements GoodsService {

    private GoodsDao goodsDao = new GoodsDaoImpl();

    @Override
    public List<Type> getType() {

        return goodsDao.getType();
    }

    @Override
    public List<Goods> getGoodsByType(String typeId) {
        return goodsDao.getGoodsByType(typeId);
    }

    /**
     * 将参数里面的数据填充到两张表中
     * service层代码应该怎么写
     * 是直接调用dao层还是service需要做逻辑
     * @param goodsParam
     */
    @Override
    public void addGoods(GoodsParam goodsParam) {
        List<Spec> specList = goodsParam.getSpecList();

        //提前加入goods表中，避免后期联合查询
        //规格中的最小值
        double price = specList.get(0).getUnitPrice();
        //取最大值
        int stockNum = specList.get(0).getStockNum();
        for (int i = 1; i < specList.size(); i++) {
            if (price > specList.get(i).getUnitPrice()) {
                price = specList.get(i).getUnitPrice();
            }
            if (stockNum < specList.get(i).getStockNum()) {
                stockNum = specList.get(i).getStockNum();
            }
        }
        goodsParam.setPrice(price);
        goodsParam.setStockNum(stockNum);

        int goodsId = goodsDao.addGoods(goodsParam);
        //spec表和goods表怎么关联？
        //goods表插入后生成的ID值要作为spec表中的goodsID值

        goodsDao.addSpecList(goodsId, specList);
    }
}
